package com.qd.system.importexcel.role;

import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.sys.domain.entity.role.RoleDTO;
import com.qd.common.sys.enums.BaseTableEnum;
import com.qd.system.model.Role;
import com.qd.system.service.dict.ExcelValidateUtil;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.role.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 角色,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
public class RoleImportHandler {

    private final RoleService roleService;
    private final ValidatorUtil validatorUtil;
    private final ExcelValidateUtil excelValidateUtil;
    private final List<ImportErr> errorList;
    private final LocalDateTime now = LocalDateTime.now();

    public RoleImportHandler(RoleService roleService, ValidatorUtil validatorUtil, List<ImportErr> errorList) {
        this.roleService = roleService;
        this.validatorUtil = validatorUtil;
        this.excelValidateUtil = new ExcelValidateUtil();
        this.errorList = errorList;
    }

    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<RoleDTO>> rowList, List<BatchResult> results) {
        final List<RoleDTO> roleList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<String> existsIds = existsIds(roleList);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<RoleDTO> excelRowMsg : rowList) {
                final RoleDTO RoleDTO = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                final List<String> errors = buildImportDto(RoleDTO);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<Role> addRoleList = new ArrayList<>(size);
                final List<Role> updateRoleList = new ArrayList<>(size);
                doProcessDictData(existsIds, roleList, addRoleList, updateRoleList);
                BatchResult.buildBatchResult(results, addRoleList.size(), updateRoleList.size());
                addRoleList.clear();
                updateRoleList.clear();
            }
        } finally {
            roleList.clear();
            existsIds.clear();
        }
    }

    /**
     * 保存数据
     *
     * @param existsIds      已经存在的数据库主键
     * @param roleList       excel行数据集合
     * @param addRoleList    添加集合
     * @param updateRoleList 更新集合
     */
    private void doProcessDictData(List<String> existsIds, List<RoleDTO> roleList, List<Role> addRoleList, List<Role> updateRoleList) {
        roleList.forEach(RoleDTO -> {
            final Role role = roleService.dtoToModel(RoleDTO);
            roleService.clearCache(role);
            if (MbUtil.isExistInCollection(existsIds, RoleDTO.getRoleId())) {
                role.setAddTime(null);
                role.setUpdateTime(now);
                updateRoleList.add(role);
            } else {
                role.setAddTime(now);
                role.setUpdateTime(null);
                addRoleList.add(role);
            }
        });
        if (!addRoleList.isEmpty()) {
            roleService.saveBatch(addRoleList);
        }
        if (!updateRoleList.isEmpty()) {
            roleService.updateBatchIds(updateRoleList);
        }
    }

    /**
     * 获得主键存在的集合
     *
     * @param roleList excel行数据集合
     * @return 主键集合
     */
    private List<String> existsIds(List<RoleDTO> roleList) {
        final List<String> ids = roleList.stream().map(RoleDTO::getRoleId).collect(toList());
        final List<String> existsIds = roleService.getBaseMapper().getIds(ids);
        ids.clear();
        return existsIds;
    }

    /**
     * 导入验证
     *
     * @param RoleDTO 单个excel行数据
     * @return 异常信息
     */
    private List<String> buildImportDto(RoleDTO RoleDTO) {
        final List<String> errors = new ArrayList<>();
        //验证信息，自己编写
        final String roleStatusDisplay = RoleDTO.getRoleStatusDisplay();
        final Integer statusValidate = MbUtil.isStatusValidate(errors, roleStatusDisplay);
        if (null != statusValidate) {
            RoleDTO.setRoleStatus(statusValidate);
        }
        final String dataScopeDisplay = RoleDTO.getDataScopeDisplay();
        final String dataScope = excelValidateUtil.isValidBase(dataScopeDisplay, BaseTableEnum.DATA_SCOPE, errors);
        if (StringUtils.hasLength(dataScope)) {
            RoleDTO.setDataScope(dataScope);
        }
        importValidate(RoleDTO, errors);
        return errors;
    }

    /**
     * 导入实体验证
     *
     * @param RoleDTO 单个excel行数据
     * @param errors  异常信息存储
     */
    private void importValidate(RoleDTO RoleDTO, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(RoleDTO, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}